<template>
  <div class="my-add-maker-box">
    <div class="searchForm">
      <a-card body-style="padding:12px" title="">
        <SchemaForm layout="vertical">
        </SchemaForm>
      </a-card>
    </div>
    <div class="my-map-box" id="map" :key="keyMap">
    </div>
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content"></div>
    </div>
  </div>
</template>
<script lang='ts' setup>
import type { FormSchema } from '@/components/core/schema-form/';

import { ref, onMounted } from 'vue'
//导入相关配置信息
import 'ol/css';
import { Map, View, Feature } from 'ol'
import { Style, Icon, Fill, Text } from 'ol/style'
import { Point } from 'ol/geom';
import { Vector as SourceVec, XYZ, } from 'ol/source'
import { Vector as LayerVec } from 'ol/layer'
import TileLayer from 'ol/layer/Tile'
import { defaults as defaultControls, } from "ol/control"
import { useForm } from '@/components/core/schema-form';
import { formatCategary2Tree, formatDept2Tree } from '@/core/permission/utils';
import { getDeptList } from '@/api/system/dept';
import { dictPotionsListApi } from '@/api/workorder/select';
import { getCategaryList } from '@/api/workorder/categary';
import { distribute } from '@/api/workorder/statisticanalysis';
import { useFormModal } from '@/hooks/useModal';
import { workorderschemas } from '../order/formSchemas';
import { listAttament } from '@/api/workorder/common/attachment';


defineOptions({
  name: '位置分布',
});


let myMap: any = null
let keyMap: any = ref(Math.random())
let vectorLayer: any = null
const [showModal] = useFormModal();
const workOrderData = ref([]);
let vectorLayers = [];



const fetchOptionList = async (params: any) => {
  const data = await dictPotionsListApi(params);
  return data.map((item) => ({
    label: item.name,
    value: item.code,
  }));
};

const loadCategaryData = async (params: any) => {
  let data = await getCategaryList(params);
  return formatCategary2Tree(data, '0');
};

const mapsearchschemass: FormSchema[] = [
  {
    field: 'selectParam',
    component: 'Input',
    label: '查询内容',
    componentProps:{
      placeholder: '工单单号/12345单号/工单内容'
    },
    colProps: {
      span: 24,
    },
  },

  {
    field: 'workOrderTypes',
    component: 'Select',
    label: '工单类型',
    colProps: {
      span: 24,
    },
    componentProps: {
      mode: 'multiple',
      request: async () => {
        return await fetchOptionList({ code: 'workorder_type' });
      },
    },
  },
  {
    field: 'industryTypes',
    component: 'Tree',
    label: '行业类型',
    colProps: {
      span: 24,
    },
    componentProps: {
      style: {
        height: '250px',
        paddingTop: '5px',
        overflow: 'auto',
        borderRadius: '6px',
        border: '1px solid #dcdfe6',
      },
      checkable: true,
      vModelKey: 'checkedKeys',
      fieldNames: {
        label: 'name',
        value: 'id',
      },
      colProps: {
        span: 12,
      },
      request: async () => {
        return await loadCategaryData({ sysCode: 'workorder', 'visible': '0', categaryCode: 'industry_type' });
      },
      getPopupContainer: () => document.body,
    },
  },
  {
    field: 'responsibleUnits',
    component: 'Tree',
    label: '责任单位',
    colProps: {
      span: 24,
    },
    componentProps: {
      style: {
        height: '250px',
        paddingTop: '5px',
        overflow: 'auto',
        borderRadius: '6px',
        border: '1px solid #dcdfe6',
      },
      checkable: true,
      vModelKey: 'checkedKeys',
      request: async () => {
        return formatDept2Tree(await getDeptList());
      },
    },
  }
]

// 初始化表单内容
const [SchemaForm, dynamicFormRef] = useForm({
  schemas: mapsearchschemass,
  actionColOptions: { span: 24 },
  submitFunc: async () => {
    let formData = {
      ...dynamicFormRef?.getFieldsValue(),
    }
    initMaker(formData);
  },
  resetFunc: async() => {
    dynamicFormRef?.setFieldsValue({
      responsibleUnits:[],
      industryTypes:[],
      workOrderTypes:[]
    })
    initMaker();
  }
});

// 描点
const initMaker = async (formData?: any) => {
    
  //移出给定的图层
  vectorLayers.forEach(item=>{
    myMap.removeLayer(item)
  })
  
  if(!formData || Object.keys(formData).length == 0 ){
    return;
  }
  workOrderData.value = await distribute(formData);

  vectorLayers = [];
  workOrderData.value.forEach(element => {
    setMarker(element)
  });
}

onMounted(() => {
  setTimeout(() => {
    myMap = new Map({
      target: 'map',
      //图层数组 layers
      layers: [
        new TileLayer({
          source: new XYZ({
            crossOrigin: 'anonymous',
            url: 'https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=a90f06c20cbb05850b3d514b6d11318a'
          })
        }),
        new TileLayer({
          source: new XYZ({
            crossOrigin: 'anonymous',
            url: 'https://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=a90f06c20cbb05850b3d514b6d11318a'
          })
        })
      ],
      //视图 View
      view: new View({
        projection: "EPSG:4326",
        center: [109.83, 40.65],
        zoom: 15,
        maxZoom: 17,
        minZoom: 1,
      }),
      //默认控件
      controls: defaultControls({
        zoom: false,
        rotate: false,
        attribution: false,
      }).extend([
        //添加新控件
        // new MousePosition(),
      ])
    })
    myMap.on('click', popupFunc)
  }, 1);
  // 添加描点数据
  initMaker();
})
// 标注点
const setMarker = (workorder: any) => {
  let point = [workorder.longitude, workorder.latitude];
  // 创建矢量容器
  let vectorSource = new SourceVec({})
  //创建图标特性
  let iconFeature = new Feature({
    geometry: new Point(point, "XY"),
    id: workorder.workOrderNumber,
  })
  //将图标特性添加进矢量中
  vectorSource.addFeature(iconFeature)
  //创建图标样式
  let iconStyle = new Style({
    image: new Icon({
      opacity: 0.75,
      src: require('@/assets/images/marker-icon.png'),
      size: [30, 65]
    }),
    text: new Text({
      text: workorder.workOrderNumber,
      fill: new Fill({
        color: '#fff',
      }),
      font: '14px Microsoft YaHei',
      offsetX: 0,
      offsetY: 30,
      padding: [2, 10, 0, 10],
      // 文本填充
      backgroundFill: new Fill({
        color: 'rgba(0,0,0,0.5)'
      })
    })
  })
  //创建矢量层
  vectorLayer = new LayerVec({
    source: vectorSource,
    style: iconStyle
  }); //添加进map
  vectorLayers.push(vectorLayer)

  myMap.addLayer(vectorLayer);
  myMap.getView().setCenter([workorder.longitude, workorder.latitude])

}

function popupFunc(evt) {
  var feature = myMap.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
    return feature
  })
  if (feature) {
    const workorderthis = workOrderData.value.filter(workorder => { return workorder.workOrderNumber == feature.values_.id })
    openMenuModal(workorderthis[0])
  }
}

/**
 * @description 打开新增/编辑弹窗
 */
const openMenuModal = async (record: Partial) => {
  const [formRef] = await showModal({
    modalProps: {
      title: `${record.id ? '查看' : '新增'}工单信息`,
      width: '80%',
      bodyStyle: { height: '60vh' },
      okButtonProps: { disabled: true },
      cancelText: '关闭',
    },
    formProps: {
      labelWidth: 100,
      schemas: workorderschemas,
    },
  });
  // 填充表单数据
  formRef?.setFieldsValue({
    ...record,
  });
  // 设置表单禁用属性
  formRef?.setSchemaFormProps({
    disabled: true,
    requiredMark: false,
  });
  // 非必填信息清除
  formRef?.updateSchema({
    field: 'remarks',
    componentProps: {
      placeholder: "",
    },
  })
  // 添加附件列表
  let data = await listAttament({ 'bussId': record.id });
  let initFileData = [];
  data.forEach((fileData) => {
    initFileData.push({
      uid: fileData.id,
      name: fileData.fileName,
      status: 'done',
    });
  })
  formRef?.updateSchema({
    field: 'attament',
    componentProps: {
      fileList: initFileData
    },
  })
};


</script>
<style scoped lang='less'>
.my-add-maker-box {
  .my-map-box {
    width: 100%;
    height: 100vh;
    margin: auto;
    z-index: 1;
  }

  .searchForm {
    position: absolute;
    width: 20vw;
    padding: 10px;
    z-index: 99;
    opacity: 0.85;
  }
}
</style>